import React, { useEffect, useState } from 'react';
import { Button, Layout, Menu, theme } from 'antd';
import { useHistory } from 'react-router-dom';
import axios from 'axios';
import { readToken } from '../util';
/** @import {ItemType, MenuItemType} from 'antd/es/menu/interface' */
/** @import {Right, Role} from '../types' */

const { Sider } = Layout;

const iconsMapping = {
    // ...
};

function SideMenu({ collapsed }) {
    const history = useHistory();
    /** @type {{role: Role}} */
    const {role} = readToken();
    const [menuList, setMenuList] = useState([]);

    // 获取菜单数据并转换格式
    const fetchMenu = async () =>  {
        const res = await axios.get("/rights?_embed=children");
        /** @type {(item: Right) => bool} */
        const checkPermission = (right) => 
            right.pagepermisson === 1 && role.rights.includes(right.key)
        /** @type {(item: Right) => ItemType<MenuItemType>} */
        const convertMenu = (right) => ({
            key: right.key,
            label: right.title,
            icon: iconsMapping[right.key],
            children: 
            (right.children && right.children.length > 0) ? 
                (right.children
                    .filter(checkPermission)
                    .map(convertMenu))
                : undefined
        });
        const result = res.data
            .filter(checkPermission)
            .map(convertMenu);
        console.log('Menu', result);
        setMenuList(result);
    };
    useEffect(() => { fetchMenu(); }, []);

    const path = history.location.pathname;
    const selectedKeys = [path];
    const openKeys = ["/" + path.split("/")[1]];

    return (
        <Sider trigger={null} collapsible collapsed={collapsed} style={{ overflow: "auto" }}>
            <div className="logo">全球新闻发布管理系统</div>
            <Menu
                theme="dark"
                mode="inline"
                selectedKeys={selectedKeys}
                defaultOpenKeys={openKeys}
                items={menuList}
                onSelect={({ item, key, keyPath, selectedKeys, domEvent }) => history.push(key)}
            />
        </Sider>
    );
}

export default SideMenu;
